#!/bin/bash

# Written by Thales A. Tsailas <ttsailas@enforcingit.com>
# Init script for the iSCSI Enterprise Target.
# http://iscsitarget.sourceforge.net/
# For Slackware Linux 

PATH=/sbin:/bin:/usr/sbin:/usr/bin
CONF=/etc/iet/ietd.conf
PID=$(pidof ietd)

RETVAL=0

start()
{
	# Load necessary modules 
	if [ ! "$PID" = '' ]; then
	  echo -en "iSCSI enterprise target is already running\n"
	else 
 	  echo -en "Loading iSCSI enterprise target module\n"
	  modprobe iscsi_trgt
	echo -en "Starting iSCSI enterprise target..."
	  /usr/sbin/ietd -c $CONF 
	  sleep 1

	    if [ $RETVAL = "0" ]; then
                echo -en "done.\n"
            else
                echo -en "failed.\n"
                exit $RETVAL
            fi
	fi

}

stop()
{
	if [ "$PID" = '' ]; then
	   echo -en "iSCSI enterprise target is not running\n"
	else 
    	   echo -en "Stoping iSCSI enterprise target...\n"
	   ietadm --op delete
	   kill -9 $PID
	   echo -en "Unloading iSCSI enterprise target modules"
	   modprobe -r iscsi_trgt
	   sleep 1
	     if [ $RETVAL = "0" ]; then
                echo -en "done.\n"
             else
                echo -en "failed.\n"
                exit $RETVAL
             fi
	fi


}

status()
{ 	
	if [ "$PID" = '' ]; then
	   echo -en "iSCSI enterprise target is not running\n"
	else 
	   echo -en "iSCSI enterprise target is running with pid: \033[1m$PID\e[0m\n"	
	   echo -en "Available targets:\n"	
	   cat /proc/net/iet/session
	fi

}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	status) 
		status
		;;
	*)
		echo "Usage: {start|stop|restart|status}" >&2
		exit 1
		;;
esac

exit 0
